package com.megvii.koala.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.megvii.koala.R;

/**
 * Created by binghezhouke on 14-1-2.
 */
public class AutoRatioImageview extends ImageView
{
    private float mRatio = -1;

    public AutoRatioImageview(Context context)
    {
        super(context);
        init(context, null);
    }

    public AutoRatioImageview(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    public AutoRatioImageview(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public void init(Context context, AttributeSet attrs)
    {
        TypedArray typedArray = context
                .obtainStyledAttributes(attrs, R.styleable.AutoRatioImageView);

        if (typedArray != null)
        {
            mRatio = typedArray.getFloat(R.styleable.AutoRatioImageView_ratio, -1.0f);
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        Drawable drawable = getDrawable();
        if (drawable != null)
        {
            int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
            if (mRatio < 0)
            {
                setMeasuredDimension(measureWidth, MeasureSpec.getSize(widthMeasureSpec) * drawable
                        .getIntrinsicHeight() / drawable.getIntrinsicWidth());
            }

            else
            {
                setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), (int) (MeasureSpec.getSize(widthMeasureSpec) * mRatio));
            }
        }
        else
        {
            setMeasuredDimension(0, 0);
        }
    }
}
